from time import sleep

import usb2IIC.usb2iic as i2c
import luinit

dev = luinit.init()
iic_config = i2c.IIC_CONFIG(400000, 1, 7, 1)
ret = i2c.IIC_Init(dev, 0, i2c.byref(iic_config))
print(ret)
# 扫描IIC总线上能正常应答的设备
SlaveAddr = (i2c.c_ushort * 128)()
SlaveAddrNum = i2c.IIC_GetSlaveAddr(dev, 0, i2c.byref(SlaveAddr))


# class WriteBuffer(object):
#     pass


if SlaveAddrNum <= 0:
    print("Get iic address faild!")
    exit()
else:
    print("Get iic address sunccess!")
    print("IIC addr:")
    for i in range(0, SlaveAddrNum):
        print("%02X " % SlaveAddr[i], end='')
    print("")
    # 向0x08地址开始连续写8字节数据
for p in range(0, 64):
    WriteBuffer = (i2c.c_byte * 10)()
    WriteBuffer[0] = p >> 5
    WriteBuffer[1] = p << 3
    for i in range(0, 8):
        WriteBuffer[2 + i] = p * 8 + i
    ret = i2c.IIC_WriteBytes(dev, 0, 0x48, i2c.byref(WriteBuffer), 10, 100)
    if ret != i2c.IIC_SUCCESS:
        print("Write iic faild!")
        exit()
    else:
        print("Write iic sunccess!")
    sleep(0.01)
# 从0x08地址开始读取8字节数据
ReadBuffer = (i2c.c_byte * 8)()
WriteBuffer[0] = 0
WriteBuffer[1] = 0x90
for i in range(0, 8):
    WriteBuffer[1 + i] = i
while True:
    ret = i2c.IIC_WriteReadBytes(dev, 0, 0x48, i2c.byref(WriteBuffer), 2, i2c.byref(ReadBuffer), 8, 100)
    if ret != i2c.IIC_SUCCESS:
        print("WriteRead iic faild!")
        exit()
    else:
        print("WriteRead iic sunccess!")
        print("Read Data:")
        for i in range(0, len(ReadBuffer)):
            print("%02X " % ReadBuffer[i], end='')
        print("")
    sleep(0.5)
# Close device
ret = i2c.USB_CloseDevice(dev)
if (bool(ret)):
    print("Close device success!")
else:
    print("Close device faild!")
    exit()
